<script lang="ts">
/**
 * @author leo
 * @description 登录页
 */

import { Component, Vue, Prop } from "vue-property-decorator";
import { Action, State, namespace } from "vuex-class";
import { EventBus } from "feok-lib";

const userModule = namespace("user");

@Component
export default class UpdatePassword extends Vue {
  get rules() {
    return {
      newPsw: [
        { required: true, message: "新密码不能为空", trigger: "blur" },
        { validator: this.validatePassWordLength, trigger: "blur" }
      ],
      rePsw: [
        { required: true, message: "再次输入新密码不能为空", trigger: "blur" },
        { validator: this.validateConfirmPassWord, trigger: "blur" }
      ]
    };
  }

  @userModule.Action("putAuthUserModpwd") public putAuthUserModpwd: any;

  public form = {
    newPsw: null,
    rePsw: null
  };

  public validatePassWordLength = (rule: any, value: any, callback: any) => {
    if (value.length < 6) {
      callback(new Error("密码长度最少6位"));
    } else {
      callback();
    }
  };

  public validateConfirmPassWord = (rule: any, value: any, callback: any) => {
    if (value !== this.form.newPsw) {
      callback(new Error("两次密码不一致"));
    } else {
      callback();
    }
  };

  public submitForm(formName: string) {
    const a = this.$refs[formName] as any;
    a.validate(async (valid: boolean) => {
      if (valid) {
        try {
          await this.putAuthUserModpwd({
            password: this.form.rePsw,
            confirmPassword: this.form.rePsw
          });
          EventBus.$emit("success", "修改成功");
        } catch (e) {
          console.log(e);
        }
      } else {
        console.log("error submit!!");
        return false;
      }
    });
  }

  public resetForm(formName: string) {
    const a = this.$refs[formName] as any;
    a.resetFields();
  }
}
</script>

<template>
  <section class="update-password">
    <div class="title">修改密码</div>
    <el-form ref="form" :model="form" label-width="150px" :rules="rules">
      <el-form-item label="新密码：" prop="newPsw">
        <el-input
          v-model="form.newPsw"
          type="password"
          style="width:300px;"
          @keyup.enter.native="onOk"
        ></el-input>
      </el-form-item>
      <el-form-item label="再次输入新密码：" prop="rePsw">
        <el-input
          v-model="form.rePsw"
          type="password"
          style="width:300px;"
          @keyup.enter.native="onOk"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">保存</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<style lang="less">
.update-password {
  background-color: #fff;
  padding: 0px 0 15px;
  .title {
    font-size: 20px;
    padding-left: 20px;
    line-height: 60px;
    border-bottom: 1px solid #dcdfe6;
    margin-bottom: 40px;
  }
}
</style>